<template>
  <div class='popup'>
    <img class='loading' src='static/loading.gif' v-show='isShowLoading' />
  </div>
</template>

<script>
import { config } from '@/config/config'
import { htmlLatexRender } from '@/utils/html-latex-render'
import VConsole from 'vconsole'
if (process.env.MODE_ENV !== 'pro') {
  new VConsole()
}

export default {
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (from.path != '/') return

      vm.isShowLoading = true
      const { token } = vm.$route.query

      if (!token) return

      const params = vm.toJson(window.atob(token))
      vm.init(params)
    })
  },
  data() {
    return {
      isShowLoading: false,
      moduleMap: new Map([
        ['homework', '/pages/homework/index/index'],
        ['exam', '/pages/exam/index/index'],
        ['homework-input', '/pages/homework-input/index/index'],
        ['wq-book', '/pages/wq-book/index/index'],
        ['exercise', '/pages/exercise/index'],
        ['learning', '/pages/learning/index'],
        ['photoSearch', '/pages/photoSearchQuestions/index'],
        ['contact', '/pages/contact/index'],
        ['daily', '/pages/daily-attendance/index'],
        ['dict-yh', '/pages/dict/index?id=1'],
        ['dict-hy', '/pages/dict/index?id=2'],
        ['dict-h', '/pages/dict/index?id=3'],
        ['dict-gh', '/pages/dict/index?id=4'],
        ['dict-ry', '/pages/dict/index?id=5'],
        ['correct-chinese', '/pages/correct/chinese/index'],
        ['correct-english', '/pages/correct/english/index'],
        ['ask-for-leave', '/pages/ask-for-leave/index'],
        ['class-guidance', '/pages/class-guidance/index']
      ])
    }
  },
  beforeCreate() {
    window.MathJye = new htmlLatexRender()
    window.android_call = {
      navigateBack: () => {
        this.$router.back()
      }
    }
  },
  created() {
  },
  mounted() {
    const { isShowLoading } = this

    if (!isShowLoading) {
      return
    }

    // 输出版本号
    console.log('version:', config.version)
    // 监听切换到后台或者设备锁屏
    document.addEventListener('visibilitychange', () => {
      const { currentModuleUse } = this.$store.state.moduleUse

      if (!document.hidden) {
        // 解锁
        // 1.平板使用时长统计-更新开始时间
        currentModuleUse.updateModuleStartTime(Date.now())
        // 2.检查token是否过期
        const { expiresTime } = this.$store.state.user
        // 如果accessToken已经过期，跳转登录页
        if (parseInt(expiresTime) < Date.now()) {
          const globalPopup = this.$popup
          globalPopup.show({
            type: 'alert',
            success: (popup) => {
              popup.$on('confirm', () => {
                globalPopup.hide('alert')

                const { android } = window

                if (android) {
                  android.toLogin()
                }
              })
              popup.setData({
                title: '提示',
                content: '登录凭证已失效，请重新登录',
                confirmText: '确认'
              })
            }
          })
        }
      } else {
        // 锁屏/退出模块
        // 平板使用时长统计-提交使用时长
        currentModuleUse.submit()
      }
    })
    // 禁止长按弹出菜单
    document.oncontextmenu = function (e) {
      return false
    }
  },
  methods: {
    toJson(str) {
      const obj = {}
      const parr = String.prototype.split.call(str, '&')
      for (let i of parr) {
        let arr = i.split('=')
        obj[arr[0]] = arr[1]
      }

      return obj
    },
    init(params) {
      const {
        module,
        tenantId,
        accessToken,
        expiresTime,
        refreshToken,
        userId,
        serialNo = ''
      } = params

      this.$store.commit('setSerialNo', serialNo)
      this.$store.commit('setTenantId', tenantId)
      this.$store.commit('setUser', {
        accessToken,
        expiresTime,
        refreshToken,
        userId
      })

      window.addEventListener('hashchange', () => {
        const hash = location.hash
        if (String.prototype.indexOf.call(hash, '/pages/redirect/index?') != -1) {
          // 返回时直接跳转主页
          const { android } = window
          android.closeWebview()
        }
      })

      const _this = this
      window.addEventListener('sw.updated', () => {
        const globalPopup = this.$popup
        globalPopup.show({
          type: 'alert',
          success: (popup) => {
            popup.$on('confirm', () => {
              globalPopup.hide('alert')

              const { android } = window

              if (android) {
                android.closeWebview()
              }
            })
            popup.setData({
              title: '新版本',
              content: '请重启模块以完成更新',
              confirmText: '确认'
            })
          }
        })
      })
      window.addEventListener('sw.ready', () => {
        // 通知安卓不再拦截断网
        const { android } = window
        android.loadComplete()
        _this.$router.push(_this.moduleMap.get(module))
      })
      if (!this.$isUseSW) {
        const { android } = window
        android
          ? this.$router.push(this.moduleMap.get(module))
          : this.$router.replace(this.moduleMap.get(module))
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.popup {
  width: 100vw;
  height: 100vh;
  position: absolute;
  left: 0;
  top: 0;
  background-color: #fff;
}

.loading {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 2000;
  width: 500px;
  height: 500px;
}
</style>
